package cn.szbo.jksystem.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.szbo.jksystem.model.User;
import cn.szbo.jksystem.service.UserService;

/**
 * UserController.java
 * 
 * @author nick xue
 * 
 *         2012-7-22 下午3:28:49
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

	private static final Logger LOGGER = Logger.getLogger(UserController.class);


	@Autowired
	private UserService userService;

	/**
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/toLogin.htm", method = RequestMethod.GET)
	public String toLogin(HttpSession session, HttpServletRequest request,
			Model model) {
		return "login";
	}

	@RequestMapping("/login.htm")
	public String getCurrentUser(Model model) {
		model.addAttribute("loginDate",
				DateFormatUtils.format(new Date(), "yyyy年MM月dd日"));
		return "frame";
	}

	@RequestMapping("/loginValidate")
	@ResponseBody
	public boolean loginValidate(HttpSession session, User user) {
		User currentUser = userService.findUser(user.getName(),
				user.getPassword());
		if (currentUser != null) {
			session.setAttribute("user", currentUser);
			LOGGER.info(user.getName() + ":验证登陆通过");
			return true;
		} else {
			LOGGER.info(user.getName()+ ":验证登陆失败");
			return false;
		}
	}

	@RequestMapping("/showUsers")
	public String getUserList(Model model) {
		model.addAttribute("users", userService.findUsers());
		return "user/users-list";
	}

	@RequestMapping("/forgetPassword")
	public String forgetPassword() {
		return "user/password";
	}

	
	@RequestMapping("/toRegesiter")
	public String toRegesiter(){
	    return "user/regesiter";
	}
	
	@RequestMapping("/validateLoginId")
	@ResponseBody
	public boolean validateLoginId(String loginId){
	    User user = userService.findUserByLoginId(loginId);
	    return user==null;
	}
	
	@RequestMapping("/regesiterUser")
	public String regesiterUser(User user){
	    userService.addUser(user);
	    return "login";
	}

}
